package freighttmpl

import (
	"context"
	// "fmt"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/moneyx"
	enum "mall/service/backend/common/enum/setting"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendCreateFreightTemplateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendCreateFreightTemplateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendCreateFreightTemplateLogic {
	return &BackendCreateFreightTemplateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// FreightTemplate management
func (l *BackendCreateFreightTemplateLogic) BackendCreateFreightTemplate(in *setting.FreightTemplateInfo) (*setting.BaseIDResp, error) {
	var data model.SysFreightTemplate
	if in.Name != nil {
		data.Name = strings.TrimSpace(*in.Name)

		if len(data.Name) == 0 {
			logx.Errorw("create freight template failed, its name is required")
			return nil, errorx.NewInvalidArgumentError("setting.freightTemplateNameRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysFreightTemplateColumns.Name] = map[string][]any{
			"equalTo": []any{data.Name},
		}
		_, count, err := l.svcCtx.FreightTemplate.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("setting.freightTemplateAlreadyExists")
		}
	}
	if in.Remark != nil {
		data.Remark = strings.TrimSpace(*in.Remark)
	}
	if in.FreeShipping != nil {
		data.FreeShipping = uint8(*in.FreeShipping)
	}
	if in.ChargeMode != nil {
		data.ChargeMode = uint8(*in.ChargeMode)
	}
	if in.Sort != nil {
		data.Sort = uint16(*in.Sort)
	}
	if in.Status != nil {
		data.Status = uint8(*in.Status)
	} else {
		data.Status = uint8(globalkey.StatusEnabled)
	}
	data.CreatedAt = time.Now()
	data.UpdatedAt = time.Now()
	rel := &model.SysFreightTemplateRel{}
	if len(in.Restrictions) > 0 {
		for _, v := range in.Restrictions {
			var restriction model.SysFreightTemplateRestriction
			if v.Regions != nil {
				restriction.Regions = null.JSONFrom([]byte(strings.TrimSpace(*v.Regions)))
			}
			if v.Mode != nil {
				restriction.Mode = uint8(*v.Mode)

				switch restriction.Mode {
				case enum.FreightTemplateRestrictionAmount:
					if v.Threshold != nil {
						if i, err := moneyx.ParseAmount(*v.Threshold); err == nil && i > 0 {
							restriction.Threshhold = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				case enum.FreightTemplateRestrictionNumber:
					if v.Threshold != nil {
						if i, err := strconv.ParseInt(*v.Threshold, 10, 32); err == nil && i > 0 {
							restriction.Threshhold = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				default:
					return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			}
			if v.Sort != nil {
				restriction.Sort = uint16(*v.Sort)
			}
			if v.Status != nil {
				restriction.Status = uint8(*v.Status)
			} else {
				restriction.Status = uint8(globalkey.StatusEnabled)
			}
			rel.Restrictions = append(rel.Restrictions, &restriction)
		}
	}
	if len(in.Rules) > 0 {
		for _, v := range in.Rules {
			var rule model.SysFreightTemplateRule
			if v.Regions != nil {
				rule.Regions = null.JSONFrom([]byte(strings.TrimSpace(*v.Regions)))
			}
			if in.ChargeMode != nil {
				rule.ChargeMode = uint8(*in.ChargeMode)

				switch rule.ChargeMode {
				case enum.FreightTemplateRuleNumber:
					if v.FirstUnit != nil {
						if i, err := strconv.ParseInt(*v.FirstUnit, 10, 32); err == nil && i > 0 {
							rule.FirstUnit = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
					if v.ContinueUnit != nil {
						if i, err := strconv.ParseInt(*v.ContinueUnit, 10, 32); err == nil && i > 0 {
							rule.ContinueUnit = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				case enum.FreightTemplateRuleWeight:
					if v.FirstUnit != nil {
						if i, err := moneyx.ParseWeight(*v.FirstUnit); err == nil && i > 0 {
							rule.FirstUnit = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
					if v.ContinueUnit != nil {
						if i, err := moneyx.ParseWeight(*v.ContinueUnit); err == nil && i > 0 {
							rule.ContinueUnit = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				case enum.FreightTemplateRuleVolume:
					if v.FirstUnit != nil {
						if i, err := moneyx.ParseVolume(*v.FirstUnit); err == nil && i > 0 {
							rule.FirstUnit = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
					if v.ContinueUnit != nil {
						if i, err := moneyx.ParseVolume(*v.ContinueUnit); err == nil && i > 0 {
							rule.ContinueUnit = uint64(i)
						} else {
							return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
						}
					}
				default:
					return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			}
			if v.FirstPrice != nil {
				if i, err := moneyx.ParseAmount(*v.FirstPrice); err == nil && i > 0 {
					rule.FirstPrice = uint64(i)
				} else {
					return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			}
			if v.ContinuePrice != nil {
				if i, err := moneyx.ParseAmount(*v.ContinuePrice); err == nil && i > 0 {
					rule.ContinuePrice = uint64(i)
				} else {
					return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
				}
			}
			if v.Sort != nil {
				rule.Sort = uint16(*v.Sort)
			}
			if v.Status != nil {
				rule.Status = uint8(*v.Status)
			} else {
				rule.Status = uint8(globalkey.StatusEnabled)
			}
			rel.Rules = append(rel.Rules, &rule)
		}
	}
	err := l.svcCtx.FreightTemplate.Insert(l.ctx, nil, &data, rel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &setting.BaseIDResp{
		Id:  data.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
